package com.topscomm.dsp.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.ResponseResult;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;

@Component
@Scope(value = "singleton")
public class DspServiceApi {
	@Value("${dsp.url.query}")
	public String queryUrl;
	@Value("${dsp.token}")
	public String token;
	private static List<String> commonParamArray = new ArrayList<>();
	static {
		commonParamArray.add("templateid");
		commonParamArray.add("pageSize");
		commonParamArray.add("pageNum");
		commonParamArray.add("paramOptional");
	}

	/**
	 * @description:查询数据
	 * @param templateId
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年8月10日上午10:56:32
	 * @modify:
	 */
	public Page query(String templateId, Map<String, Object> paraMap) {
		String resultJsonString = postRequest(templateId, paraMap);
		return handlerData(resultJsonString);
	}

	/**
	 * @description:发送post请求
	 * @param url
	 * @param templateId
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年8月10日上午10:25:24
	 * @modify:
	 */
	public String postRequest(String templateId, Map<String, Object> paraMap) {
		try {
			// 请求体，增加共通传入参数
			Map<String, Object> paramsMap = new HashMap<>();
			paraMap.keySet().forEach(key -> {
				if (!commonParamArray.contains(key)) {
					paramsMap.put(key, paraMap.get(key));
				}
			});
			paraMap.put("templateid", templateId);
			paraMap.put("paramOptional", true);
			paraMap.put("paramsMap", paramsMap);
			String bodyJson = JSONObject.toJSONString(paraMap);
			HttpResponse response = HttpRequest.post(queryUrl).header("Accept", "*/*", false).header("Content-Type", "application/json").header("token", token)
					.body(bodyJson).execute();
			int status = response.getStatus();
			if (status == HttpStatus.HTTP_OK)
				return response.body();
			else
				throw new BusinessException("接口请求失败：状态码(" + status + ")，" + response.body());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("接口请求异常：" + e.getMessage());
		}
	}

	/**
	 * @description: 处理数据，返回要使用的data
	 * @param json
	 * @return
	 * @author: lizhengliang
	 * @date: 2020年7月27日下午5:59:08
	 * @modify:
	 */
	private Page handlerData(String json) {
		try {
			ResponseResult<JSONObject> result = JSON.parseObject(json, ResponseResult.class);
			if (result == null) {
				throw new BusinessException("接口调用失败");
			}
			if (!result.isSuccess()) {
				throw new BusinessException(result.getMessage());
			}
			JSONObject resultObj = result.getResult();
			return JSON.parseObject(resultObj.toJSONString(), Page.class);
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
	}
}
